package cn.tedu.cwgl.service.impl;

import cn.tedu.cwgl.entity.Insurance;
import cn.tedu.cwgl.entity.UserInfo;
import cn.tedu.cwgl.mapper.InsuMapper;
import cn.tedu.cwgl.service.InsuService;
import cn.tedu.cwgl.util.Config;
import cn.tedu.cwgl.util.PageModel;
import cn.tedu.cwgl.util.Result;
import cn.tedu.cwgl.util.ResultUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class InsuServiceImpl implements InsuService {

    @Resource
    private InsuMapper insuMapper;

    @Override
    public Result<Insurance> getInsurance(PageModel model) {
        List<Insurance> insurances = insuMapper.getInsurance(model);
        if (insurances.size() >= 0) {
            Result<Insurance> result = ResultUtil.success(insurances);
            result.setTotal(insuMapper.getTotalInsu(model));
            if (result.getTotal() == 0) {
                result.setMsg("查询不到任何相关数据");
            } else {
                result.setMsg("数据获取成功");
            }
            return result;
        } else {
            return ResultUtil.unSuccess("数据获取失败");
        }
    }

    private UserInfo getSessionUser(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(Config.CURRENT_USERNAME);
        userInfo.setPassword(null);
        return userInfo;
    }

    @Override
    public int addInsurance(Insurance insurance, HttpSession session) {

        UserInfo userInfo1 = getSessionUser(session);
        System.out.println(userInfo1.getId());

        insurance.setUserid(userInfo1.getId());


        int result = insuMapper.addInsurance(insurance);
        System.out.println(insurance);


        return result;
    }


    @Override
    public int delInsurance(Insurance insurance, HttpSession session) {
        UserInfo userInfo1 = getSessionUser(session);
        System.out.println(userInfo1.getId());

        insurance.setUserid(userInfo1.getId());
        int result = insuMapper.delInsurance(insurance);
        System.out.println(insurance);
        return result;
    }

    @Override
    public int updateInsurance(Insurance insurance, HttpSession session) {
        UserInfo userInfo1 = getSessionUser(session);
        System.out.println(userInfo1.getId());

        insurance.setUserid(userInfo1.getId());
        int result = insuMapper.updateInsurance(insurance);
        System.out.println(insurance);
        return result;
    }
}